<?php
require_once 'BaseController.php';
require_once APPLICATION_PATH.'/models/Cate.php';

class CateController extends BaseController{

    public function listAction(){
        $tblcate = new Cate();
        $cates = $tblcate->getCates();
        $this->view->cates = $cates;
    }

    public function editAction(){
        $id = $this->getCheckedId();
        $tblcate = new Cate();
        $this->view->act = 'edit';
        if(($this->view->cate = $tblcate->getCateById($id)) == null){
            //分类不存在
            header('Location:'.ADMIN_PATH.'/Cate/list');
            exit;
        }
    }

    public function addAction(){
        $this->view->act = 'add';
        $this->view->cate = array(
            'id' => '',
            'name' => '',
            'order' => '',
        );
        $this->render('edit');
    }

    public function delAction(){
        $id = $this->getCheckedId();
        $tblcate = new Cate();
        if($tblcate->deletecate($id)<1){
            //删除失败
        }else {
            //删除成功
        }
        header('Location:'.ADMIN_PATH.'/Cate/list');
        exit;
    }

    public function doupdateAction(){
        $act = $this->_getParam('act');
        $tblcate = new Cate();
        $set = array(
            'name' => $this->_getParam('name'),
            'order' => $this->_getParam('order'),
        );

        if($act == 'edit'){
            $id = $this->getCheckedId();
            $affected = $tblcate->updatecate($id, $set);
            if($affected == 0){
                echo '更新无效：您没有对内容进行任何更改！';
            }else if($affected == 1){
                echo '更新成功！';
            }else{
                echo '更新失败！请认真检查您所填写的内容！';
            }

        }
        else if($act == 'add'){
            if($tblcate->addcate($set)<1){
                //添加失败
            }else {
                //添加成功
            }
        }
        else{
            //无效操作
        }
        header('Location:'.ADMIN_PATH.'/Cate/list');
        exit;
    }

    private function getCheckedId(){
        $id = $this->_getParam('id');
        if(!is_numeric($id)){
            //参数不合法
            header('Location:'.ADMIN_PATH.'/Cate/list');
            exit;
        }
        return $id;
    }

}
